package com.gitee.wsl.doc.prosemirror.model.fragment.ext

import com.gitee.wsl.doc.prosemirror.model.fragment.Fragment
import com.gitee.wsl.doc.prosemirror.model.node.Node




@Suppress("ReturnCount")
fun insertInto(content: Fragment, dist: Int, insert: Fragment, parent: Node? = null): Fragment? {
    val (index, offset) = content.findIndex(dist).run { index to offset }
    val child = content.maybeChild(index)
    if (offset == dist || child!!.isText) {
        if (parent != null && !parent.canReplace(index, index, insert)) return null
        return content.cut(0, dist).append(insert).append(content.cut(dist))
    }
    val inner = insertInto(child.content, dist - offset - 1, insert, null) ?: return null
    return content.replaceChild(index, child.copy(inner))
}

fun Fragment.insert( dist: Int, insert: Fragment, parent: Node? = null): Fragment?
              = insertInto(this,dist,insert,parent)